/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imclient;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 * Class for the UI side of IM Client.
 *
 * @author andrew
 */
public class IMClientForm extends javax.swing.JFrame {

    //Declare some constants here 
    final User user = new User();
    
    //create attribues of IMClientForm
    String errorMessage;
    String version;
    String lblSendTxt;
    String title;
    String adminUser;

    /**
     * Creates new form IMClientForm
     */
    public IMClientForm() {
        initComponents();

        //set the title here




        //Attempt to read the XML File and assign some attributes to objects. 
        //
        try {

            XMLReader reader = new XMLReader();
            HashMap<String, String> hash = reader.readXML("config.xml");

            //Create some string objects from what was found in the HashMap
            title = hash.get("title");
            version = hash.get("version");
            lblSendTxt = hash.get("lblSend");
            errorMessage = hash.get("errorMessage");
            adminUser = hash.get("adminUser");

            //Assign attrubutes to the String objects we created above
            //set the title here
            this.setTitle(title);
            //set the send button label here 
            sendBtn.setText(lblSendTxt);
            //set the username of the final user object here
            user.setUserName(hash.get("username") + ": ");


        } catch (Exception e) {
            Logger.getLogger(IMClientForm.class.getName()).log(Level.SEVERE, null, e);
        }



    }
    /**
     * Create new Message object here to be public but have private attributes
     * accessed by getters and setters
     *
     */
    Message thisMessage = new Message();
    Message recievedMessage = new Message();

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nestedFrame = new javax.swing.JInternalFrame();
        messageLable1 = new javax.swing.JLabel();
        sendBtn = new javax.swing.JButton();
        currentMessageTxt = new javax.swing.JTextField();
        messageHistoryLst = new java.awt.List();
        txtAdvertisements = new javax.swing.JTextField();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                formAncestorResized(evt);
            }
        });

        nestedFrame.setVisible(true);
        nestedFrame.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                nestedFrameAncestorResized(evt);
            }
        });

        messageLable1.setText("Messages ");

        sendBtn.setText("Send");
        sendBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendBtnActionPerformed(evt);
            }
        });

        currentMessageTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                currentMessageTxtActionPerformed(evt);
            }
        });

        txtAdvertisements.setEditable(false);

        javax.swing.GroupLayout nestedFrameLayout = new javax.swing.GroupLayout(nestedFrame.getContentPane());
        nestedFrame.getContentPane().setLayout(nestedFrameLayout);
        nestedFrameLayout.setHorizontalGroup(
            nestedFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(nestedFrameLayout.createSequentialGroup()
                .addGroup(nestedFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(messageHistoryLst, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtAdvertisements, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(nestedFrameLayout.createSequentialGroup()
                        .addComponent(messageLable1)
                        .addGap(0, 471, Short.MAX_VALUE))
                    .addGroup(nestedFrameLayout.createSequentialGroup()
                        .addComponent(currentMessageTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendBtn)
                        .addGap(95, 95, 95)))
                .addGap(61, 61, 61))
        );
        nestedFrameLayout.setVerticalGroup(
            nestedFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(nestedFrameLayout.createSequentialGroup()
                .addComponent(messageLable1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(messageHistoryLst, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addGroup(nestedFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentMessageTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendBtn))
                .addGap(7, 7, 7)
                .addComponent(txtAdvertisements, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(93, Short.MAX_VALUE))
        );

        getContentPane().add(nestedFrame, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*This snippet of code allows the internal frame to inhertit the bounds of the Jframe
     * IE allows for the form to be resize freindly
     */
    private void formAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formAncestorResized
        // TODO add your handling code here:
        this.nestedFrame.setBounds(this.rootPane.getBounds());
    }//GEN-LAST:event_formAncestorResized

    private void nestedFrameAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_nestedFrameAncestorResized
        // TODO add your handling code here:
    }//GEN-LAST:event_nestedFrameAncestorResized

    /*
     * Contains actions to be performed upon clicking sendBtn (Send Button)
     */
    private void sendBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendBtnActionPerformed
        // TODO add your handling code here:


        //Get the current message text
        currentMessageTxt.selectAll();
        String message = currentMessageTxt.getSelectedText();
        //set the content of thisMessage to the content of the string placed into the text box
        thisMessage.setContent(message);
        //set the owner of the sent message
        thisMessage.setSender(user);
        //new ChatServiceStub object 
        IChatService stub = new ChatServiceStub();
        
        //set the message content to contain the username and message to be sent
        String content = user.getUserName() + thisMessage.getContent();
        
        //send the message(in a way)
        messageHistoryLst.add(content);

        


        try {
            //alert for sent message
            JOptionPane.showMessageDialog(rootPane, stub.sendMessage(thisMessage));
            
            //initialize recievedMessage object
            recievedMessage = stub.receiveMessage();
            //add that content to the message history
            messageHistoryLst.add(adminUser+": "+recievedMessage.getContent());
        
        } catch (Exception ex) {
            //Logger.getLogger(IMClientForm.class.getName()).log(Level.SEVERE, null, ex);

            JOptionPane.showInputDialog(errorMessage);

        }



    }//GEN-LAST:event_sendBtnActionPerformed

    /*
     * This method works the same as sendBtnActionPerformed. This is the configuration for when users hit the 
     * ENTER key when typing a message
     */
    private void currentMessageTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_currentMessageTxtActionPerformed
        // TODO add your handling code here:
        

       //Get the current message text
        currentMessageTxt.selectAll();
        String message = currentMessageTxt.getSelectedText();
        //set the content of thisMessage to the content of the string placed into the text box
        thisMessage.setContent(message);
        //set the owner of the sent message
        thisMessage.setSender(user);
        //new ChatServiceStub object 
        IChatService stub = new ChatServiceStub();
        
        //set the message content to contain the username and message to be sent
        String content = user.getUserName() + thisMessage.getContent();
        
        //send the message(in a way)
        messageHistoryLst.add(content);

        


        try {
            //alert for sent message
            JOptionPane.showMessageDialog(rootPane, stub.sendMessage(thisMessage));
            
            //initialize recievedMessage object
            recievedMessage = stub.receiveMessage();
            //add that content to the message history
            messageHistoryLst.add(adminUser+": "+recievedMessage.getContent());
        
        } catch (Exception ex) {
            //Logger.getLogger(IMClientForm.class.getName()).log(Level.SEVERE, null, ex);

            JOptionPane.showInputDialog(errorMessage);

        }

    }//GEN-LAST:event_currentMessageTxtActionPerformed

    /*
     * Inner class of IMClientForm. Implements runnable. Used to generate advertisements.  
     * Create new thread to utilize this class
     * 
     */
    class AdvertisementRotator implements Runnable {

        private IAdvertisementEngine engine = new AdvertisementEngineStub();

        /*
         * This is the method implementation of the runnable interface.
         *  Calls the getAdvertisement() method to select advertisement, displays for ten seconds
         * and then selects a new advertisement. After all advertisements have been utilized the method
         * hides the advertising strip. 
         * 
         *@param null
         * @return void
         */
        @Override
        public void run() {

            int i = 1;

            while (i > 0) {
                txtAdvertisements.setText(engine.getAdvertisement());
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(IMClientForm.class.getName()).log(Level.SEVERE, null, ex);
                }
                i++;
                while (i >= 10) {
                    boolean hide = false;
                    txtAdvertisements.setVisible(hide);
                }
            }





        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IMClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IMClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IMClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IMClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new IMClientForm().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField currentMessageTxt;
    private javax.swing.JLabel jLabel1;
    private java.awt.List messageHistoryLst;
    private javax.swing.JLabel messageLable1;
    private javax.swing.JInternalFrame nestedFrame;
    private javax.swing.JButton sendBtn;
    private javax.swing.JTextField txtAdvertisements;
    // End of variables declaration//GEN-END:variables
}
